/**
 * jwt认证拦截
 * @authors 杨兴洲（of2502）
 * @date    2017/2/27 11:58
 * @version 1.0
 */

import * as jwt from "jsonwebtoken";

export default (req, res, next) => {
    let token = req.headers['authorization'] || req.body.token || req.query.token;
    // todo: 没有校验签名，不安全
    let decoded = jwt.decode(token, {complete: true});
    try {
        const {exp, sub: userID} = decoded.payload;
        // console.log(userID);
        if (+new Date > exp * 1000) {
            return res.status(200).json({
                errcode: 90000,
                errmsg: "token过期,禁止访问!"
            });
        }
        res.locals.userID = userID;
        console.log("用户编号", userID);
        next();
    } catch (err) {
        res.status(200).json({
            errcode: 99999,
            errmsg: "token错误,禁止访问!"
        });
    }
}
